<?php

namespace app\forms\role;

use Yii;
use yii\db\Exception;
use app\models\Role;
use yii\web\HttpException;

/**
 * 角色 创建
 */
class CreateForm extends BaseForm
{
    public $setDefault = false;

    public function rules()
    {
        $rules = parent::rules();
        return array_merge($rules, [
            ['name', 'unique', 'targetClass' => Role::class, 'message' => '名称被占用'],

            ['setDefault', 'boolean'],
        ]);
    }

    /**
     * @param $param
     * @throws HttpException
     */
    public static function create($param)
    {
        $form = new self();
        $form->setAttributes($param);
        !$form->validate() ? $form->validateError() : '';

        try {
            $att = $form->getAttributes();
            $att['key'] = mt_rand(100000, 999999);
            $att['author_id'] = Yii::$app->getUser()->getId();

            // 角色
            $role = new Role;
            $role->setAttributes($att);
            $role->save(false);

            // 权限
            $role->addItem($form->item, $form->auth, $form->data);

            // 设置为默认
            if ($form->setDefault)
                $role->addDefaultItem($form->item, $form->auth, $form->data);

            // casbin 操作

        } catch (Exception $e) {
            $form->serverError();
        }

        $form->createOk();
    }
}